package com.hjn.springboot.springbootinterceptor.timer;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.concurrent.Executors;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

/**
 * @author huaijn
 * @date 2022/5/5 /0005-14:23
 * @description todo
 */
@Configuration
@EnableScheduling
@EnableAsync
public class DynamicScheduleTask implements SchedulingConfigurer {

  @Async
  @Override
  public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
    //设置的线程池corePoolSize，自己根据业务需求设定
    taskRegistrar.setScheduler(Executors.newScheduledThreadPool(5));
    taskRegistrar.addTriggerTask(() ->
    {
      try {
        System.out.println("休眠10秒"+LocalDateTime.now().toLocalTime());
        Thread.sleep(10000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      System.out.println(Thread.currentThread().getName() + "执行动态定时任务1: " + LocalDateTime.now().toLocalTime());
    },
        new Trigger() {
          @Override
          public Date nextExecutionTime(TriggerContext triggerContext) {
            String cron = "0/6 * * * * ?";
            CronTrigger trigger = new CronTrigger(cron);
            return trigger.nextExecutionTime(triggerContext);
          }
        }
    );
  }
}
